<template>
  <div class="page-box h100 display-flex czbj dfddsrttre">
    <div class="mb10 display-flex">
      <div class="dfssrra">
        <n-button @click="downloadXLSX">下载模版</n-button>
      </div>
      <div class="ml10">
        <n-button @click="showModal = true">导入</n-button>
      </div>
      <div class="ml10">
        <n-button @click="daochukmse">导出</n-button>
      </div>
    </div>

    <dxtable :dataJson="dataJson" :portUrl="portUrl" :qx="qx" :formJson="formJson" :headBtn="headBtn"
      @addFromback="addFromback" :czFun="czFun" ref="dxtableRef"></dxtable>
    <n-modal v-model:show="showModal" preset="card" class="dsfsdretree">
      <template #header>
        <div>导入</div>
      </template>
      <div>
        <n-alert title="温馨提示" type="warning">
          批量导入会导致生成二维码卡顿,如需打印二维码，需要导入成功后30秒后刷新列表选择打印
        </n-alert>
      </div>
      <template #action>
        <div class="tr display-flex">
          <n-upload @before-upload="uploadxl" accept=".xls, .xlsx">
            <n-button type="primary" :loading="dftte">导入</n-button>
          </n-upload>
          <n-button class="ml20" @click="showModal = false"> 取消 </n-button>
        </div>
      </template>
    </n-modal>

    <n-modal v-model:show="showModaler" preset="card" class="Stock-diagnosis" style="width:400px !important">
      <template #header>
        <div>二维码浏览</div>
      </template>
      <div>
        <img :src="qcimgll" class="w100"/>
      </div>
      <template #action>
        <div class="tr">
          <n-button @click="showModaler=false"> 关闭 </n-button>
        </div>
      </template>
    </n-modal>
  </div>
</template>

<script lang='ts' setup>
import { dxget, dxpost, transferTimeYMDHm } from "../../util";
import { h, ref, reactive } from "vue";
import { NButton, NAlert, NStep, NSteps } from "naive-ui";
import dxtable from "../../components/util/dxtable.vue";
const showModal = ref(false);
const showModaler = ref(false)
let portUrl = "ks/ksproductlist";
const dftte = ref(false);
const dxtableRef = ref();
const qcimgll = ref()
const forms = ref({
  zzW: 400,
  zzH: 400,
});
const lableArray = ref([]);
const printSetup = ref(["qcCode"]);
if (localStorage.forms) {
  forms.value = JSON.parse(localStorage.forms);
  printSetup.value = JSON.parse(localStorage.printSetup);
  lableArray.value = JSON.parse(localStorage.lableArray);
}
let dataJson = reactive([
  {
    title: "产品编码",
    key: "productCode",
    search: true,
  },
  {
    title: "型号",
    key: "model",
    search: true,
  },
  {
    title: "容量",
    key: "capacity",
    search: true,
    render(row) {
      return row.capacity + "mAh";
    },
  },

  {
    title: "电压",
    key: "voltage",
    search: true,
    render(row) {
      return row.voltage + "V";
    },
  },
  {
    title: "内阻",
    key: "internalResistance",
    search: true,
    render(row) {
      return row.internalResistance + "mΩ";
    },
  },
  // {
  //   title: "功耗",
  //   key: "powerDissipation",
  //   search: true,
  // },

  {
    title: "过流",
    key: "overcurrent",
    search: true,
    render(row) {
      return row.overcurrent + "A";
    },
  },
  {
    title: "短路延迟",
    key: "Shortcircuitdelay",
    search: true,
    render(row) {
      return row.Shortcircuitdelay + "ms";
    },
  },
  {
    title: "尺寸",
    key: "size",
    search: true,
  },
  {
    title: "生产日期",
    key: "dateManufacture",
    width: 180,
  },

  {
    title: "添加时间",
    key: "addTime",
    width: 180,
    type: "date",
  },
  // {
  //   title: "二维码",
  //   key: "qcCode",
  //   render(row) {
  //     return h("img", {
  //       class: "qcCode",
  //       src: row.QRCode,
  //     });
  //   },
  // },
]);
let timejw = new Date().getTime();
let formJson = ref([
  {
    title: "产品编码",
    key: "productCode",
    type: "input",
    required: true, // 是否为必填
  },
  {
    title: "型号",
    key: "model",
    type: "input",
    required: true, // 是否为必填
  },
  {
    title: "容量",
    key: "capacity",
    type: "input",
    required: true, // 是否为必填
  },

  {
    title: "电压",
    key: "voltage",
    type: "input",
    required: true, // 是否为必填
  },
  {
    title: "内阻",
    type: "input",
    key: "internalResistance",
    required: true, // 是否为必填
  },
  // {
  //   title: "功耗",
  //   type: "input",
  //   key: "powerDissipation",
  //   required: true, // 是否为必填
  // },

  {
    title: "过流",
    key: "overcurrent",
    type: "input",
  },
  {
    title: "短路延迟",
    key: "Shortcircuitdelay",
    required: true, // 是否为必填
    type: "input",
  },
  {
    title: "尺寸",
    key: "size",
    required: true, // 是否为必填
    type: "input",
  },

  {
    title: "生产日期",
    type: "datetime",
    key: "dateManufacture",

    val: new Date().getTime(),
    required: true,
  },
]);
const addFromback = async (data) => {
  if (data) {
    await dxget("ks/index/getQRCode", { id: data });
  }
};
const downloadXLSX = () => {
  window.location.href =
    "https://duxinggj-1251133427.cos.ap-guangzhou.myqcloud.com/kangsheng/%E5%BA%B7%E7%9B%9B%E8%AE%BE%E5%A4%87%E5%88%97%E8%A1%A8.xlsx";
};
const uploadxl = (data) => {
  readExcel(data.file.file);
};
const readExcel = (file) => {
  // 解析Excel
  return new Promise(function () {
    // 返回Promise对象
    const reader = new FileReader();
    reader.onload = async (e) => {
      // 异步执行
      var data = e.target.result;
      let wb = window.XLSX.read(data, {
        type: "binary",
      });
      let worksheet = JSON.stringify(
        window.XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
      );
      console.log(worksheet);
      let worksheetarr = JSON.parse(worksheet);
      let kjhsd = [];
      const lijne = [];
      worksheetarr.map((a, b) => {
        const obj = {
          productCode: "",
          model: "",
          internalResistance: "",
          voltage: "",
          capacity: "",
          powerDissipation: "",
          dateManufacture: "",
        };
        for (let key in a) {
          switch (key) {
            case "产品编码":
              obj.productCode = a[key];
              break;
            case "型号":
              obj.model = a[key];
              break;
            case "内阻":
              obj.internalResistance = a[key];
              break;
            case "电压":
              obj.voltage = a[key];
              break;
            case "容量":
              obj.capacity = a[key];
              break;
            case "功耗":
              obj.powerDissipation = a[key];
              break;
            case "生产日期":
              obj.dateManufacture = a[key];
              break;
          }
        }
        lijne.push(obj);
      });

      dftte.value = true;
      const { errno }: any = await dxpost("ks/index/bulkImport", {
        list: JSON.stringify(lijne),
      });
      dftte.value = false;
      showModal.value = false;
      if (errno == 0) {
        window.$message.success("导入成功！");
        dxtableRef.value.initDataExpose();
      } else {
        window.$message.error("导入失败！");
      }
    };
    reader.readAsBinaryString(file);
  });
};

const daochukmse = async () => {
  const { data }: any = await dxget("ks/index/export");
  const arrs = [];
  const arrst = [];
  dataJson.map((a) => {
    if (a.title != "操作" && a.title != "添加时间" && a.title != "二维码") {
      arrst.push(a.title);
    }
  });

  arrs.push(arrst);

  data.map((a) => {
    const jjneer = [];
    dataJson.map((b) => {
      if (b.key != "addTime" && b.key != "qcCode") {
        jjneer.push(a[b.key]);
      }
    });
    arrs.push(jjneer);
  });

  let jhhs = window.XLSX.utils.aoa_to_sheet(arrs);
  let workbook = window.XLSX.utils.book_new();
  console.log(jhhs);
  console.log(workbook);
  window.XLSX.utils.book_append_sheet(workbook, jhhs, "第一页");
  window.XLSX.writeFile(workbook, "产品列表.xlsx");
};
// let headBtn = [
//   {
//     name: "批量打印 ",
//     async clickFun(row) {
//       const { data }: any = await dxget("ks/index/getBatchQuery", {
//         id: row.join(","),
//       });
//       // printQR(data);
//     },
//   },
// ];

const printQR = (data, load?) => {
  return new Promise((resolve) => {
    // window.getLodop();
    window.LODOP.SET_PRINT_PAGESIZE(0, forms.value.zzW, forms.value.zzH, "");
    console.log(data);
    data.map((a) => {
      CreateOnePage(a);
    });

    // window.LODOP.SET_PREVIEW_WINDOW(0, 0, 0, 600, 400, "");
    window.LODOP.PREVIEW();
    try {
      load.value = false;
    } catch (e) { }
  }).catch((e) => {
    window.$message.error("正在加载打印控件请稍后操作！");
    try {
      load.value = false;
    } catch (e) { }
  });
};

const CreateOnePage = (row) => {
  window.LODOP.NewPage();

  lableArray.value.map((a) => {
    printSetup.value.map((b) => {
      if (a.value == b) {
        if (b == "qcCode") {
          window.LODOP.ADD_PRINT_IMAGE(
            a.y,
            a.x,
            a.h,
            a.w,
            "<img border='0' src='" + row.QRCode + "' />"
          );
          window.LODOP.SET_PRINT_STYLEA(0, "Stretch", 2);
        } else {
          window.LODOP.ADD_PRINT_TEXT(
            a.y,
            a.x,
            a.w,
            a.h,
            a.name + ":" + row[a.value]
          );
          window.LODOP.SET_PRINT_STYLEA(0, "FontSize", a.size);
        }
      }
    });
  });
};

const czFun = {
  fun: (row, loading) => {
    return [
      h(
        NButton,
        {
          type: "info",
          quaternary: true,
          onClick: async (e) => {
            showModaler.value = true
            qcimgll.value = row.QRCode
            // await printQR([row], loading);
          },
        },
        "浏览"
      ),
    ];
  },
};

const qx = {
  DeletePermissionID: "comsenzparticularsdel", //删除
  EditPermissionIdentifier: "comsenzparticularsbj", // 编辑
  NewPermissionIdentifier: "comsenzparticularsxz", // 新建
  ViewPermissionID: "comsenzparticularsck", // 查看
};
</script>